﻿using System;
using System.Collections.Generic;
using System.Text;
using GroupChat2013.Common;
using GroupChat2013.Interface;
using GroupChat2013.Logic;
using GroupChat2013.Logic.Interface;
using GroupChat2013.Data;

namespace GroupChat2013.Main.Components
{
    public class GroupChatReceiveProcess : IReceiveProcess
    {
        private FrmChatBox frmChatBox;

        private FrmMain frmMain;

        private GroupNotifyRepository m_GroupNotifyRepository;

        /// <summary>
        /// 消息处理标志
        /// </summary>
        private string key;

        private string groupId = "groupId";

        private string name = "name";

        private string unread = "unread";

        /// <summary>
        /// 构造函数
        /// </summary>
        public GroupChatReceiveProcess(FrmChatBox frmChatBox, FrmMain frmMain)
        {
            this.frmChatBox = frmChatBox;
            this.frmMain = frmMain;

            key = ConstClass.GETLATESTGROUPCHAT;
        }

        public bool Process(Entity.Protocol.TransferMsgInfo message)
        {
            if (!message.action.Equals(key))
                return false;

            if (message.data.ContainsKey(groupId))
            {
                string id = message.data[groupId];
                IChat chat = EngineContext.Current.ChatManager[id];
                if (chat != null)
                {
                    chat.UpdateChat();
                }
                else
                {
                    if (m_GroupNotifyRepository == null)
                        m_GroupNotifyRepository = new GroupNotifyRepository(EngineContext.Current.FilePathManager.DbPath);

                    //是否气泡提示
                    if (m_GroupNotifyRepository.IsExistGroup(id))
                    {
                        int count = 0;
                        int.TryParse(message.data[unread], out count);
                        frmMain.NotifyGroupHasNewMsg(id, count);
                    }
                    else
                    {
                        frmChatBox.AddItem(id, message.data[name], message.data[unread], Entity.ChatType.Group);
                    }
                }
            }

            return true;
        }
    }
}
